import { MatchDefine } from "../../../kds-base-define/src/MatchDefine";
import { DB } from "../db";
import { ServerValues } from "../../../kds-base-define/src/ServerConfig";

let redis = DB.redis
let groupTableName = "t_group"
async function addGroup(h:string,groupData:MatchDefine.GroupData) {
	await redis.hset(groupTableName,groupData.groupID.toString(),groupData,true)
	return true 
}

async function getGroup(h:string,groupID:number) {
	let groupData:MatchDefine.GroupData = await redis.hget(groupTableName,groupID.toString(),true)
	return groupData
}

async function removeGroup(h:string,groupID:number) {
	await redis.hdel(groupTableName,groupID.toString())
	return true 
}

async function getAllGroups(h:string) {
	let dict = await redis.hgetall(groupTableName,true)
	if(dict == null) {
		return null
	}
	let ret:MatchDefine.GroupData[] = []
	for(let key of Object.keys(dict)) {
		let value = dict[key]
		ret.push(value)
	}
	return ret 
}

export let RpcGroup = {
	add:addGroup,
	get:getGroup,
	remove:removeGroup,
	getAll:getAllGroups,
}

let db = DB.get(ServerValues.dbRoom,"match")
let matchTableName = "t_match"
async function addMatch(h:string,matchData:MatchDefine.MatchData) {
	let data = await getMatch(h,matchData.matchID)
	if(data) {
		return false 
	}
	return await db.insert(matchTableName,matchData) > 0
}

async function getMatch(h:string,matchID:number) {
	let data:MatchDefine.MatchData = await db.getSingle(matchTableName,{matchID:matchID})
	return data 
}

async function updateMatch(h:string,matchData:MatchDefine.MatchData) {
	return await db.update(matchTableName,{matchID:matchData.matchID},matchData) >= 0
}

async function removeMatch(h:string,matchID:number) {
	await db.del(matchTableName,{matchID:matchID})
	await removeMatchRealtime(h,matchID)
}

async function getAllMatches(h:string) {
	let datas:MatchDefine.MatchData[] = await db.get(matchTableName,{})
	return datas == null ? [] : datas
}

async function updateMatchRealtime(h:string,realtime:MatchDefine.MatchRealtime) {
	await redis.hset(matchTableName,realtime.matchID.toString(),realtime,true)
	return true 
}

async function getMatchRealtime(h:string,matchID:number) {
	let data:MatchDefine.MatchRealtime = await redis.hget(matchTableName,matchID.toString(),true)
	return data 
}

async function removeMatchRealtime(h:string,matchID:number) {
	await redis.hdel(matchTableName,matchID.toString())
}

export let RpcMatch = {
	add:addMatch,
	get:getMatch,
	update:updateMatch,
	remove:removeMatch,
	getAll:getAllMatches,
}

export let RpcMatchRealtime = {
	update:updateMatchRealtime,
	get:getMatchRealtime,
}